<?php
namespace app\service;
use app\model\MemberThirdOauthModel;
use EasyWeChat\Factory;
use support\facade\Logger;
use const support\CORRECT;
use const support\THIRD_OAUTH_TYPE_1;

class WechatPayService
{

    //获取小程序支付参数（分账版）
    public static function getToPayParamsWithDivideAccounts(int $memberId,string $outTradeNo,string $tradeType,float $totalFee,string $orderTitle,int $profitSharing=1)
    {
        $totalFee=$totalFee*100;
        $notifyUrl=sprintf("%s/%s",env('WECHAT_PAY_CALLBACK_URL',''),$outTradeNo);
        Logger::app('支付：获取支付参数','info',[$memberId,$outTradeNo,$tradeType,$totalFee,$notifyUrl,$orderTitle]);
        //获取微信小程序标识
        $openid=MemberThirdOauthModel::where([
            'member_id'=>$memberId,
            'third_type'=>THIRD_OAUTH_TYPE_1,
            'status'=>CORRECT
        ])->value('third_openid');
        Logger::app('支付：获取微信小程序标识','info',[$openid]);
        if (!$openid){
            Logger::app('支付：微信小程序标识为空');
            return false;
        }
        $config=config('wechat.wechat_pay');
        Logger::app('支付：微信小程序支付配置','info',$config);
        //初始化配置
        $app = Factory::payment($config);
        $data=[
            'body'              => $orderTitle,
            'out_trade_no'      => $outTradeNo,
            'total_fee'         => $totalFee,
            'notify_url'        => $notifyUrl,
            'trade_type'        => $tradeType,
            'openid'            => $openid,
            'profit_sharing'    =>$profitSharing?'Y':'N'
        ];
        Logger::app('支付：初始化配置支付数据','info',$data);
//        $app->rebind('cache', $cache);
        $result = $app->order->unify($data);
        Logger::app('支付：获取支付结果','info',$result);
        if (empty($result['prepay_id'])){
            return false;
        }
        $prepay_id=$result['prepay_id']??'';
        $data=$app->jssdk->bridgeConfig($prepay_id);
        Logger::app('支付：二次验签数据','info',[$data]);
        return json_decode($data,true);
    }

}